package core.proto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.FileUtils;

public class FileDownload {

	public static void Download(String downloadUrl) {

		URL dl = null;
		File fl = null;
		try {
			fl = new File(app.constants.CollabVizConstants.LOCAL_DIRECTORY+downloadUrl);
			dl = new URL(InfoViz.codebase().toString() + downloadUrl);
			FileUtils.copyURLToFile(dl, fl);
			if(downloadUrl.endsWith("zip")) {
				ZipFile zf = new ZipFile(fl);
				Enumeration e = zf.entries();
				while (e.hasMoreElements()) {
					ZipEntry ze = (ZipEntry) e.nextElement();
					System.out.println("Unzipping " + ze.getName());

					if(ze.isDirectory()) {
						// This is not robust, just for demonstration purposes.
						(new File(app.constants.CollabVizConstants.LOCAL_DIRECTORY+ze.getName())).mkdir();
						continue;
					}

					if(!ze.getName().equals("HTML/.DS_Store")) {
						FileOutputStream fout = new FileOutputStream(app.constants.CollabVizConstants.LOCAL_DIRECTORY
								+ze.getName());
						InputStream in = zf.getInputStream(ze);
						for (int c = in.read(); c != -1; c = in.read()) {
							fout.write(c);
						}
						in.close();
						fout.close();
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
